package com.jz.community.basecomm.utils.permission;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;


import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.utils.DialogUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * @author weilu
 */
public class PermissionUtil {

    private final Context context;
    private final RxPermissions mRxPermissions;
    private final String hint;
    private final String[] permissions;
    private final RequestPermission mRequestPermission;

    private PermissionUtil(Builder builder) {
        this.hint = builder.hint;
        this.context = builder.context;
        this.permissions = builder.permissions;
        this.mRxPermissions = builder.mRxPermissions;
        this.mRequestPermission = builder.callbacks;
        startRequest();
    }

    /**
     * 批量请求sdk6.0 dangerous permission
     *
     * @param listner     权限申请状态监听
     * @param permissions 批量权限数组 全部已经授权
     */

    @TargetApi(Build.VERSION_CODES.M)
    public static void handleRunTimePermis(Activity act,
                                           PermissionResultListener listner,
                                           String... permissions) {
        PermissionUtil.with(act)
                .setRxPermissions(new RxPermissions(act))
                .request(permissions)
                .callBack(new PermissionUtil.RequestPermission() {
                    @Override
                    public void onRequestPermissionSuccess() {
                        listner.onResultPermissionListener();
                    }

                    @Override
                    public void onRequestPermissionFailure() {
                        if (!act.isFinishing()){
                            act.finish();
                        }
                    }
                })
                .build();
    }

    /**
     * 部分6.0 无法获取CHANGE_NETWORK_STATE权限
     * 可以去开启WRITE_SETTINGS权限
     */
    private boolean checkSettingPermission(Context context) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
            return Settings.System.canWrite(context);
        }
        return true;
    }

    private void startRequest() {
        List<String> newPermissions = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            if (permissions[i].equals(Manifest.permission.WRITE_SETTINGS)) {
                if (!checkSettingPermission(context)) {
                    showSettingPermissionDialog();
                    return;
                }
            } else {
                newPermissions.add(permissions[i]);
            }
        }

        mRxPermissions.request(newPermissions.toArray(new String[newPermissions.size()]))
                .subscribe(aBoolean -> {
                    // Always true pre-M
                    if (aBoolean) {
                        mRequestPermission.onRequestPermissionSuccess();
                    } else {
                        showMissingPermissionDialog();
                    }
                });
    }

    /**
     * 显示提示信息
     */
    private void showSettingPermissionDialog() {
        new DialogUtils(context, "当前应用缺少必要权限。\n\n请点击\"设置\"-\"允许修改系统设置").setOnDialogClickListener(new DialogUtils.OnDialogClickListener() {
            @Override
            public void onLeftClick() {
                mRequestPermission.onRequestPermissionFailure();
            }

            @Override
            public void onRightClick() {
                if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
                    Uri selfPackageUri = Uri.parse("package:" + context.getPackageName());
                    Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
                            selfPackageUri);
                    context.startActivity(intent);
                }
            }
        });
    }

    /**
     * 显示提示信息
     */
    private void showMissingPermissionDialog() {
        new DialogUtils(context, hint).setOnDialogClickListener(new DialogUtils.OnDialogClickListener() {
            @Override
            public void onLeftClick() {
                mRequestPermission.onRequestPermissionFailure();
            }

            @Override
            public void onRightClick() {
                new PermissionSetting().execute(context);
            }
        });
    }

    public interface RequestPermission {
        /**
         * 权限请求成功
         */
        void onRequestPermissionSuccess();

        /**
         * 权限请求失败
         */
        void onRequestPermissionFailure();
    }

    public interface PermissionResultListener {

        void onResultPermissionListener();
    }

    /**
     * 确保申请摄像头权限时，有写入外部存储的权限。
     */
    public static PermissionUtil.Builder with(Context context) {
        return new PermissionUtil.Builder(context);
    }

    public static class Builder {

        private final Context context;
        private RxPermissions mRxPermissions;
        private String hint = "当前应用缺少必要权限。\n\n请点击\"设置\"-\"权限\"-打开所需权限。";
        private String[] permissions;
        private RequestPermission callbacks;

        private Builder(Context context) {
            this.context = context;
        }

        public Builder setRxPermissions(RxPermissions mRxPermissions) {
            this.mRxPermissions = mRxPermissions;
            return this;
        }

        public Builder request(String... permissions) {
            this.permissions = permissions;
            return this;
        }

        public Builder callBack(RequestPermission callbacks) {
            this.callbacks = callbacks;
            return this;
        }

        public Builder setHint(String hint) {
            this.hint = hint;
            return this;
        }

        public void build() {
            if (context == null) {
                throw new IllegalArgumentException("Context must not be null.");
            }
            if (mRxPermissions == null) {
                throw new IllegalStateException("RxPermissions needs to be set!");
            }
            if (permissions == null) {
                throw new IllegalStateException("permissions needs to be set!");
            }
            if (callbacks == null) {
                throw new IllegalArgumentException("callbacks must not be null.");
            }
            new PermissionUtil(this);
        }
    }

}
